package cn.wqb.bpp.common.utils.task;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TaskQueue {

    //队列：排列进入操作池
    public Queue<Task> queue = new LinkedList<>();
    private int maxQueueSize;

    //操作池：并行处理订单的查询工作
    public List<Task> workingPool = new ArrayList<>();
    private int maxWorkingSize;

    public TaskQueue(int maxQueueSize, int maxWorkingSize) {
        this.maxQueueSize = maxQueueSize;
        this.maxWorkingSize = maxWorkingSize;
    }

    public boolean isQueueFull() {
        return queue.size() >= maxQueueSize;
    }

    public boolean isPoolFull() {
        return workingPool.size() >= maxWorkingSize;
    }

    public boolean addTask(Task task, boolean useQueueSizeLimit) {
        boolean canAddTask = true;
        if(useQueueSizeLimit){
            canAddTask = !isQueueFull();
        }
        if (canAddTask) {
            //如果处理池已满，先加入队列，否则加入处理池
            if (isPoolFull()) {
                queue.offer(task);
            } else {
                workingPool.add(task);
                task.startWork();
            }
            return true;
        }
        return false;
    }

}
